<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {
	function __construct(){
		parent::__construct();
		$this->load->helper('url');
		$this->load->library('auth');
		if (!$this->auth->is_Login()) {
			redirect("user/login");
			exit();
		}
		if (!$this->auth->is_Admin()) {
			redirect("home");
			exit();
		}
		$this->load->library("form_validation");
		$this->load->helper(array("url","form", 'my_data_helper'));
		$this->load->model('article_model');
	}


	public function articles($page = 1)
	{
		$total = $this->article_model->num_rows();
		$nb_record_page = 10;

		//--- Paging
		$this->load->library('pagination');
		$config['base_url'] = site_url("admin/articles");
		$config['total_rows'] = $total;
		$config['per_page'] = $nb_record_page;
		$config['uri_segment'] = 3;
		$config['num_links'] = 2;
		$config['use_page_numbers'] = TRUE;

		$config['cur_tag_open'] = '<div  class="btn btn-default btn-info">';
		$config['cur_tag_close'] = '</div>';

		$config['num_tag_open'] = '';
		$config['num_tag_close'] = '';

		$config['last_tag_open'] = '';
		$config['last_tag_close'] = '';

		$config['next_tag_open'] = '';
		$config['next_tag_close'] = '';

		$config['first_tag_open'] = '';
		$config['first_tag_close'] = '';

		$config['prev_tag_open'] = '';
		$config['prev_tag_close'] = '';

		$config['next_link'] = FALSE;
		$config['prev_link'] = FALSE;

		$config['first_link'] = '&lsaquo;&nbsp;&nbsp;First';
		$config['last_link'] = 'Last&nbsp;&nbsp;&rsaquo;';

		$config['anchor_class'] = 'class="btn btn-default a_btn" style="text-decoration: none;"';

		$this->pagination->initialize($config);

		$data['pagination'] = $this->pagination->create_links();

		//$data['user_data'] = $this->user_model->getInfo($this->session->userdata('userid'));
		$data['articles'] = $this->article_model->getAllArticle($nb_record_page * ($page - 1), $nb_record_page);
		$this->load->view('logged_in/admin/articles', $data);
	}
	public function users($page = 1)
	{
		$total = $this->user_model->num_rows();
		$nb_record_page = 10;

		//--- Paging
		$this->load->library('pagination');
		$config['base_url'] = site_url("admin/users");
		$config['total_rows'] = $total;
		$config['per_page'] = $nb_record_page;
		$config['uri_segment'] = 3;
		$config['num_links'] = 2;
		$config['use_page_numbers'] = TRUE;

		$config['cur_tag_open'] = '<div  class="btn btn-default btn-info">';
		$config['cur_tag_close'] = '</div>';

		$config['num_tag_open'] = '';
		$config['num_tag_close'] = '';

		$config['last_tag_open'] = '';
		$config['last_tag_close'] = '';

		$config['next_tag_open'] = '';
		$config['next_tag_close'] = '';

		$config['first_tag_open'] = '';
		$config['first_tag_close'] = '';

		$config['prev_tag_open'] = '';
		$config['prev_tag_close'] = '';

		$config['next_link'] = FALSE;
		$config['prev_link'] = FALSE;

		$config['first_link'] = '&lsaquo;&nbsp;&nbsp;First';
		$config['last_link'] = 'Last&nbsp;&nbsp;&rsaquo;';

		$config['anchor_class'] = 'class="btn btn-default a_btn" style="text-decoration: none;"';

		$this->pagination->initialize($config);

		$data['pagination'] = $this->pagination->create_links();

		//$data['user_data'] = $this->user_model->getInfo($this->session->userdata('userid'));
		$data['users'] = $this->user_model->getAllData($nb_record_page * ($page - 1), $nb_record_page);
		$this->load->view("logged_in/admin/users", $data);
	}

	public function editUser($id = 0) {
		$this->form_validation->set_rules("name","Full name","required|min_length[6]");
		//$this->form_validation->set_rules("username","Username","required|max_length[25]|callback_checkUser");
		//$this->form_validation->set_rules("password","Password","required|matches[repassword]");
		$this->form_validation->set_rules("address","Address");
		$this->form_validation->set_rules("gender","Gender");
		$this->form_validation->set_rules("active","Active");

		if($this->form_validation->run()==FALSE){
			$data['user'] = $this->user_model->getInfo($id);
			$data['error'] = '';
			$this->load->view("logged_in/admin/editUser",$data);
		}
		else
		{

			$add = array(
				"name" => $this->input->post("name"),
				//"password"  => md5($this->input->post("password")),
				"address"   => $this->input->post("address"),
				"active"    => $_POST['active'],
				"gender"    => $_POST['gender'],
				"level"     => $_POST['level']
			);
			//var_dump($add);
			//exit;
			//--- Xử lý ảnh : phần này không bắt buộc
			$img = "";
			$flag = TRUE;
			if($_FILES['image']['name'] != NULL){
				$config['upload_path']   = './images/avatar/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['encrypt_name']  = true; // ma hoa ten file
				$config['remove_spaces'] = true; // xoa khoang trang
				$this->load->library('upload', $config);

				if(!$this->upload->do_upload("image"))
				{
					$data['error'] = $this->upload->display_errors();
					$data['user'] = $this->user_model->getInfo($id);
					$this->load->view("logged_in/admin/editUser",$data);
					$flag = FALSE;
				}
				else
				{
					$img = $this->upload->data();
					$add['image'] = $img['file_name'];
				}
			}
			if($flag==TRUE){
				//--- thanh cong
				if($this->user_model->updateUser($add,$_POST['id'])){
					$data['user'] = $this->user_model->getInfo($id);
					$data['error'] = 'Update successful!';
					$this->load->view("logged_in/admin/editUser",$data);
				}
			}
		}
	}

	public function addUser() {
		$this->form_validation->set_rules("name","Full name","required|min_length[6]");
		$this->form_validation->set_rules("username","Username","required|max_length[25]|callback_checkUser");
		$this->form_validation->set_rules("password","Password","required|matches[repassword]");
		$this->form_validation->set_rules("email","Email","required|valid_email|callback_checkEmail");
		$this->form_validation->set_rules("address","Address");
		$this->form_validation->set_rules("gender","Gender","required");

		if($this->form_validation->run()==FALSE){

			$this->load->view("logged_in/admin/addUser");
		}
		else
		{

			$salt = create_random_string(5);
			$add = array(
				"name" => $this->input->post("name"),
				"username"  => $this->input->post("username"),
				"salt"      => $salt,
				"password"  => md5($this->input->post("password")),
				"email"     => $this->input->post("email"),
				"address"   => $this->input->post("address"),
				"level"     => $_POST['level'],
				"gender"    => $_POST['gender'],
				"add_date"  => time(),
				"active"    => 0, // chua kich hoat
			);

			//--- Xử lý ảnh : phần này không bắt buộc
			$img = "";
			$flag = TRUE;
			if($_FILES['image']['name'] != NULL){
				$config['upload_path']   = './images/avatar/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['encrypt_name']  = true; // ma hoa ten file
				$config['remove_spaces'] = true; // xoa khoang trang
				$this->load->library('upload', $config);

				if(!$this->upload->do_upload("image"))
				{
					$data['error'] = $this->upload->display_errors();
					$this->load->view("logged_in/admin/addUser",$data);
					$flag = FALSE;
				}
				else
				{
					$img = $this->upload->data();
					$add['image'] = $img['file_name'];
				}
			}

			if($flag==TRUE){
				//--- Gui mail kich hoat neu add thanh cong
				$message = "";
				if($this->user_model->addUser($add)){

					$userid = mysql_insert_id();
					$link_active = base_url()."user/active/?userid=".$userid."&key=".md5($salt);
					$message  = "Please follow this link to active your acount <br/>";
					$message .= "Link : <a href=".$link_active.">".$link_active."</a><br/>";
					$message .= "username : ".$add['username']."<br/>";
					$message .= "password : ".$this->input->post("password");


					$this->load->library("email");
					$this->email->from('tmptmp268@gmail.com', 'YourBlog Email System');
					$this->email->to($add['email']);

					$this->email->subject('Active your account!');
					$this->email->message($message);

					$this->email->send();

					$this->session->set_userdata(array($this->_register => TRUE));
					redirect("admin/users");
				}
			}
		}

	}

	public function deleteUser($id = 0) {
		$this->user_model->deleteUser($id);
		redirect("/admin/users");
	}

	function editArticle($id = 0) {
		$data['error'] = '';
		if(isset($_POST['btn_edit'])) {
			$success = TRUE;
			//content & title
			$data  = array(
				"title" => $this->input->post("title"),
				"content" => $this->input->post("content")
			);
			if(!$this->article_model->updateArticle($data,$id))
				$success = FALSE;
			else
				$data['error'] = "Error on update article!";

			//image
			$img = "";
			if($_FILES['image']['name'] != NULL){
				//xoa avatar cu
				$img = 'images/avatar/'.$this->user_model->getInfo($this->session->userdata('userid'))['image'];
				if(file_exists($img))
					unlink($img);
				//upload file moi
				$config['upload_path']   = './images/article_image/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['encrypt_name']  = true; // ma hoa ten file
				$config['remove_spaces'] = true; // xoa khoang trang
				$this->load->library('upload', $config);

				if(!$this->upload->do_upload("image"))
				{
					$data['error'] .= '<br/>'.$this->upload->display_errors();
					$success = FALSE;
				}
				else
				{
					$img = $this->upload->data();
					$add['image'] = $img['file_name'];

					if(!$this->article_model->updateArticle($add, $id)) {
						$data['error'] .= "<br/>Failed on change image.";
						$success = FALSE;
					}
				}

			}
			if($success == TRUE)
				redirect('admin/editArticle/'.$id);
			else {
				$data['article'] = $this->article_model->get_article($id);
				$this->load->view("logged_in/admin/editArticle",$data);

			}
		}
		$data['article'] = $this->article_model->get_article($id);
		$this->load->view("logged_in/admin/editArticle",$data);
	}

	public function deleteArticle($id = 0) {
		$this->article_model->deleteArticle($id);
		redirect("/admin/articles");
	}
}
